<template>
  <div>
    <el-form-item
      label="商品图片:"
      prop="region"
      class="uploadImg"
    >
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/system/common/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :on-change="onChange"
        ref="upload"
      >
        <img
          width="50px"
          height="50px"
          v-if="imageUrl"
          :src="imageUrl"
          class="avatar"
        ></img>
        <i
          v-else
          class="el-icon-plus avatar-uploader-icon"
        ></i>
      </el-upload>
    </el-form-item>
  </div>
</template>

<script>
import { VueCropper } from "vue-cropper";

export default {
  components: { VueCropper },
  data() {
    return {
      imageUrl: undefined,
    };
  },
  methods: {
    handleAvatarSuccess (response, file, fileList) {
      // 拼接down接口预览
      this.imageUrl = `http://localhost:8080/system/common/download?name=${response.data}`
      console.log(this.imageUrl)
    },
    onChange (file) {
      if(file){
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if(['png','jpeg','jpg'].indexOf(suffix) < 0){
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if(!size){
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },
  }
};
</script>
<style scoped lang="scss">
</style>
